import { AnyAction } from "redux";
import * as TYPES from "../action-types";
import LOGIN_TYPES from "../../typings/login-types";
export interface ProfileState {
  loginState: LOGIN_TYPES; //当前用户的登录状态
  user: any; //当前已经登录的用户信息
  error: string | null; //错误信息
}
let initialState: ProfileState = {
  //初始状态
  loginState: LOGIN_TYPES.UN_VALIDATE, //当前用户的登录状态
  user: null, //当前已经登录的用户信息
  error: null, //错误信息
};
export default function (
  state: ProfileState = initialState,
  action: AnyAction
): ProfileState {
  switch (action.type) {
    case TYPES.VALIDATE:
      if (action.payload.success) {
        //如果此用户已经登录了
        return {
          ...state,
          loginState: LOGIN_TYPES.LOGINED,
          user: action.payload.data, //设置用户名
          error: null, //没有错误
        };
      } else {
        return {
          ...state,
          loginState: LOGIN_TYPES.UNLOGIN,
          user: null, //用户名为空
          error: action.payload, //错误对象赋值
        };
      }
    case TYPES.LOGOUT:
      return {
        ...state,
        loginState: LOGIN_TYPES.UN_VALIDATE,
        user: null,
        error: null
      };
    case TYPES.CHANGE_AVATAR: 
      return {
        ...state,
        user: {
          ...state.user,
          avatar: action.payload
        }
      };
    default:
      return state;
  }
}